import React, { FC, useState, useEffect } from "react";
// import {produce} from 'immer'
// import QuestionCard from "../../components/QuestionCard.tsx";
import { useSearchParams } from "react-router-dom";
import { useTitle,useRequest } from "ahooks";
import { Typography,Empty,Table,Tag,Space,Button,Modal,Spin, message,} from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import ListSearch from '../../components/ListSearch.tsx'
import useLoadQuestionListData from '../../hooks/useLoadQuestionListData.ts'
import { updateQuestionService,deleteQuestionsService } from '../../service/question.ts'
import SelfPagination from '../../components/SelfPagination.tsx'
import "./common.css";
// 组件是一个函数（执行返回 JSX 片段），组件初次渲染执行这个函数
// 任何 state 更新，都会触发组件的更新（重新执行函数）
const { Title } = Typography;
const { confirm } = Modal
const Star: FC = () => {
    useTitle("小董问卷-回收站");
    const [searchParams] = useSearchParams();
    console.log("keyword", searchParams.get("keyword"));
    useEffect(() => {
        return () => {};
    }, []); // 无依赖，组件初次渲染时执行

    // const [count, setCount] = useState(0)
    // const [questionList, setQuestionList] = useState([
    //     {id: "q1",title: "问卷1",isPublished: false,isStar: true,answerCount: 10,createAt: "2025-04-10",},
    //     {id: "q2",title: "问卷2",isPublished: true,isStar: false,answerCount: 11,createAt: "2025-05-11",},
    //     {id: "q3",title: "问卷3",isPublished: false,isStar: false,answerCount: 12,createAt: "2025-06-12",},
    //     {id: "q4",title: "问卷4",isPublished: true,isStar: true,answerCount: 13,createAt: "2025-07-13",},
    // ]);

    // useEffect(() => {
    //   console.log('question list changed')
    // }, [questionList])

    // 2、hooks模式
    const { data = {}, loading, refresh } = useLoadQuestionListData({ isDeleted: true })
    const { list = [], total = 0 } = data 

    // 列
    const columns = [
        { title:'标题',dataIndex:'title',key:'title' },
        { title:'是否发布',dataIndex:'isPublished', render:(isPublished:boolean)=>{
            return isPublished ? <Tag color="processing">已发布</Tag> : <Tag>未发布</Tag>
        },key:'isPublished' },
        { title:'答卷',dataIndex:'answerCount',key:'answerCount' },
        { title:'创建时间',dataIndex:'createdAt',key:'createdAt' },
    ] 
    const [selectedRowKeys,setSelectedIds] = useState<string[]>([])

    const del = ()=>{
        confirm({
            title:'确认彻底删除该问卷?',
            icon: <ExclamationCircleOutlined />,
            content:'删除以后不可以找回',
            onOk: deleteQuestion
        })
    }

    const { run: deleteQuestion } = useRequest(
        async ()=> await deleteQuestionsService(selectedRowKeys),
        {
            manual: true,
            debounceWait:500,
            onSuccess:()=>{
                message.success('删除成功')
                refresh() // 手动刷新列表
                setSelectedIds([])
            }
        }
    )
    // 恢复
    const {run:recover} = useRequest(
        async ()=>{
            for await (const id of selectedRowKeys){
                await updateQuestionService(id, { isDeleted: false })
            }
        },{
            manual: true,
            debounceWait:500,
            onSuccess:()=>{
                message.success('恢复成功')
                refresh() // 手动恢复列表
                setSelectedIds([])

            }
        }
    )
    const TableElem = (
        <>
            <div style={{ marginBottom:'10px'}}>
                <Space>
                    <Button type="primary" disabled={selectedRowKeys.length === 0} onClick={recover}>恢复</Button>
                    <Button danger disabled={selectedRowKeys.length === 0} onClick={del}>彻底删除</Button>
                </Space>
            </div>
            <Table 
                rowKey={(r:any) => r.id} 
                dataSource={list} 
                pagination={false} 
                columns={columns} 
                rowSelection={{
                    type: 'checkbox',
                    onChange: (selectedRowKeys:any) => {
                        console.log('selectedRowKeys',selectedRowKeys)
                        setSelectedIds(selectedRowKeys as string[])
                    }
                }} />
                
        </>
    )
    return (
        <div>
            <div className="ListHeader">
                <div className="left">
                    <Title level={3}>回收站</Title>
                </div>
                <div className="right">
                    <Title level={3}><ListSearch /></Title>
                </div>
            </div>
            <div className="ListContent">
                {loading && (<div style={{textAlign:'center'}}><Spin /></div>)}
                {!loading && list.length === 0 && <Empty description="暂无数据" />}
                {!loading && list.length > 0 && TableElem}
            </div>
            <div className="ListFooter">
            <SelfPagination total={total} />
            </div>
        </div>
    );
};

export default Star;
